package com.lwl.blog.web.controller;

import com.lwl.blog.core.exception.JsonException;
import com.lwl.blog.core.utils.R;
import com.lwl.blog.web.entity.InvitataionEntity;
import com.lwl.blog.web.entity.UserEntity;
import com.lwl.blog.web.service.CommentService;
import com.lwl.blog.web.service.InvitationService;
import com.lwl.blog.web.service.UserService;
import com.lwl.blog.web.service.impl.LikeService;
import com.lwl.blog.web.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/invitationController")
public class InvitationController {

    @Autowired
    private InvitationService invitationService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @PostMapping("/publish")
    @ResponseBody
    public R publish(@RequestBody InvitataionEntity invitataionEntity, HttpSession session) throws Exception {

        //1.获取用户信息
        UserEntity loginUser = (UserEntity) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new JsonException(100, "登录超时，请重新登陆!");
        }

        //2.封装用户信息
        invitataionEntity.setUserId(loginUser.getId());
        boolean save = invitationService.save(invitataionEntity);

        return R.out(save);

    }


    @GetMapping("/info/{id}")
    public String info(@PathVariable Integer id, Model model, HttpSession session) throws Exception {

        //1.通过帖子id查询帖子信息
        InvitataionEntity invitataionEntity = invitationService.getById(id);

        //2.查询作者信息
        Integer userId = invitataionEntity.getUserId();
        UserEntity userEntity = userService.getById(userId);

        // 3.查询帖子的评论
        List<CommentVo> commentEntityList = commentService.commentListByInvitataionId(invitataionEntity.getId());

        //4.查看帖子点赞数量
        Long count = likeService.getInvitataionLikeCount(id);

        //5.从session获取yonghuid
        UserEntity loginUser = (UserEntity) session.getAttribute("loginUser");
        //声明用户点赞状态
        Boolean likeStatus = false;
        //判断用户是否对当前得帖子点赞
        if (loginUser!=null){
            likeStatus=likeService.getInvitataionUserLike(loginUser.getId(),id);
        }


        // 4.把帖子的数据和作者的数据放到map中
        model.addAttribute("topic", invitataionEntity);
        model.addAttribute("user", userEntity);
        model.addAttribute("commentVoList", commentEntityList);
        model.addAttribute("likeCount",count);// 帖子的点赞数量
        model.addAttribute("likeStatus", likeStatus ? 1 : 0); // 当前用户是否对这个帖子已经点过赞了

        //4.调用试图层做渲染
        return "view/site/discuss-detail";

    }
}
